const express = require('express');
var fs = require('fs');
var multer = require('multer');
var path = require('path');
const router = express.Router();
const serve = 'https://dingshiyuan123.cn/web/api'
// const serve = 'http://localhost:3000/web/api'
const Common = require('../util/common')
const Constant = require('../constant/constant')

var storage = multer.diskStorage({

    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '../uploads/'))  //设定文件上传路径
    },
    //给上传文件重命名，获取添加后缀名
    filename: function (req, file, cb) {
        var fileFormat = file.originalname.split("."); //采用分割字符串，来获取文件类型
        console.log(fileFormat)
        var extname = path.extname(file.originalname); //path下自带方法去获取文件类型
        // cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]); //更改名字
        cb(null, fileFormat[0] + '-' + Date.now() + extname); //更改名字
    }
});
var upload = multer({ storage: storage }) //定制化上传参数

//单个文件上传
router.post('/single', upload.single('avatar'), (req, res) => {
    const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
    if (req.file) {
        let index = req.file.path.indexOf("/uploads")
        let filepath = serve + req.file.path.slice(index)
        resObj.data = filepath
        res.json(resObj)
    } else {
        res.json(Constant.DEFAULT_ERROR)
    }
});

//多个文件上传
router.post('/many', upload.array('photos', 5), (req, res) => {
    const resObj = Common.clone(Constant.DEFAULT_SUCCESS);
    if (req.files.length > 0) {
        let filepath = []
        req.files.forEach((item, index) => {
            filepath[index] = item.path.indexOf("/uploads")
            filepath[index] = serve + item.path.slice(filepath[index])
        });
        resObj.data = filepath
        res.json(resObj)
    } else {
        res.json(Constant.DEFAULT_ERROR)
    }
});
module.exports = router;